#include "Log.h"
#include <string.h>
#include <boost/filesystem.hpp>
#include <boost/log/sources/logger.hpp>  
#include <boost/log/sources/record_ostream.hpp>  
#include <boost/log/sources/global_logger_storage.hpp>  
#include <boost/log/utility/setup/file.hpp>  
#include <boost/log/utility/setup/common_attributes.hpp>  
#include <boost/log/sinks/text_ostream_backend.hpp>  
#include <boost/log/attributes/named_scope.hpp>  
#include <boost/log/expressions.hpp>  
#include <boost/log/support/date_time.hpp>  
#include <boost/log/detail/format.hpp>  
#include <boost/log/detail/thread_id.hpp>
#include <boost/log/sinks/sink.hpp>
#include <boost/log/sinks/async_frontend.hpp>

using namespace std;
namespace logging = boost::log;
namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;
namespace sinks = boost::log::sinks;
namespace attrs = boost::log::attributes;

BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(my_logger, logging::sources::severity_logger_mt<logging::trivial::severity_level>)

Logger::Logger(const std::string& sink) : m_SinkName(sink), m_log(keywords::channel = sink)
{
	Init(sink);
}

Logger::~Logger()
{
}

void Logger::Init(const std::string& log_path)
{
	// create logging core frame
	boost::shared_ptr<logging::core> core = logging::core::get();

	// create a asynchronous sink
	typedef sinks::asynchronous_sink<sinks::text_file_backend> TextSink;

	// create the backend
	boost::shared_ptr<sinks::text_file_backend> bluestore = boost::make_shared<sinks::text_file_backend>(
		keywords::file_name = "/var/log/" + log_path + "_%Y_%m_%d.log",
		keywords::rotation_size = 10 * 1024 * 1024,
		keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0),
		keywords::min_free_space = 30 * 1024 * 1024);

	// add backend to sink
	boost::shared_ptr<TextSink>object(new TextSink(bluestore));

	// set the rotated files will be stored
	object->locked_backend()->set_file_collector(sinks::file::make_collector(
		keywords::target = "logs",
		keywords::max_size = 16 * 1024 * 1024,
		keywords::min_free_space = 100 * 1024 * 1024));
	object->locked_backend()->scan_for_files();

	// create the sink formatter
	object->set_formatter(
			expr::format("%1%-[%2%]-(%3%)(%4%): %5%")
			% expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")
			% expr::attr<logging::trivial::severity_level>("Severity")
			% expr::attr<attrs::current_thread_id::value_type >("ThreadID")
			% expr::attr<unsigned int>("LineID")
			% expr::message);

	// add sink to core frame
	core->add_sink(object);

	// common attribute
	logging::add_common_attributes();
}

